/**
 * 
 */
package com.ntv.presentation.servlet;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import com.ntv.domain.IContent;
import com.ntv.service.DomainException;
import com.ntv.service.content.IContentAppService;

/**
 * @author localadmin
 * 
 */
public class ContentServlet extends DispatcherServlet {

	public IContentAppService getContentAppService() {	
		BeanFactory beanFactory = new ClassPathXmlApplicationContext("nammatv.spring.service.xml"); 		
		return (IContentAppService) beanFactory.getBean("contentAppService");
	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try {
			IContent content = getContentAppService().findConent(1L);
			ServletOutputStream out = response.getOutputStream();
			InputStream stream = content.getContent();
			Integer length = stream.available();
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];

			while ((length = stream.read(buffer)) != -1) {
				System.out.println("writing " + length + " bytes");
				out.write(buffer, 0, length);
			}
			response.setContentType(content.getContentType());
			stream.close();
			out.flush();
		} catch (DomainException e) {
			e.printStackTrace();
		}
	}
}
